//
//  WBNetWorkManager.swift
//  个人微博
//
//  Created by 任聪聪 on 2017/10/6.
//  Copyright © 2017年 任孜聪. All rights reserved.
//

import UIKit
import AFNetworking
enum requestType {
    case GET
    case POST
}
//倒入框架的文件名字
//网络管理工具
class WBNetWorkManager: AFHTTPSessionManager {
    //swift 中枚举可以为任意类型
    //静态区／常量／闭包／在第一次执行闭包时将结果保存在shared常量中
    static let shared = WBNetWorkManager()
    lazy var userAccount = WBUserAccount()
    //用户登录标记
    var userLogin:Bool {
        return userAccount.access_token != nil
    }
    //访问令牌拼接方法
    func AcessTokenRequest(type:requestType = .GET,URLString: String,parameters:[String:Any]?,completion:@escaping (_ json:AnyObject?,_ isSucess:Bool)->()) {
        var parameters = parameters
        //判断accessToke是否为空,accessToken在程序执行过程中一般不为nil
        guard let token = userAccount.access_token else {
            print("访问令牌不存在，请重新登录")
            //FIXME:(发送消息，重新登录)
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
            completion(nil, false)
            return
        }
        //判断字典是否存在如果不存在新建一个字典
        if parameters == nil {
            parameters = [String:Any]()
        }
        parameters?["access_token"] = token
        requestData(type: type, URLString: URLString, parameters: parameters as! [String : AnyObject], completion: completion)
    }
    //利用一个函数封装AFN发起 GET／POST网络请求
    
    /// <#Description#>
    ///
    /// - Parameters://利用一个函数封装AFN发起 GET／POST网络请求
    ///   - type: 枚举类型 GET/POST
    ///   - URLString: 新浪微博接口地址
    ///   - parameters: accessToken
    ///   - completion: 闭包回调返回值
    func requestData(type:requestType = .GET,URLString: String,parameters:[String:AnyObject],completion:@escaping (_ json:AnyObject?,_ isSucess:Bool)->()) {
        //成功的闭包回调
        let sucess = { (task:URLSessionTask,json:Any)->() in
            //通过闭包回调返回结果值
            completion(json as AnyObject, true)
        }
        //失败的闭包回调
        let failure = { (task:URLSessionTask?,error:Error)->() in
            //针对403错误代码，处理acessToken过期情况
            if (task?.response as? HTTPURLResponse)?.statusCode == 403{
                print("acessToken过期，请重新登录")
                //FIXME:(此方法不知道被谁调用，发送通知，谁收到谁处理)
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: "bad acesstoken")
            }
            print("网络请求错误\(error)")
            completion(nil, false)
        }
        if type == .GET {
            get(URLString, parameters: parameters, progress: nil, success: sucess, failure:failure)
        }else{
            post(URLString, parameters: parameters, progress: nil, success: sucess, failure:failure)
        }
        

    }
}
